package com.ljt.handler;

import cn.hutool.core.util.RandomUtil;
import com.google.code.kaptcha.Producer;
import com.ljt.common.constant.CommonConstants;
import com.ljt.common.constant.MqQueueConstant;
import com.ljt.common.message.MobileMsgTemplate;
import com.ljt.common.utils.BaseResultGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.HandlerFunction;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import zipkin2.reporter.amqp.RabbitMQSender;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author administrator
 * @date 2019/07/25
 * 验证码生成逻辑处理类
 */
@Slf4j
@Component
@AllArgsConstructor
public class SmsCodeHandler implements HandlerFunction<ServerResponse> {
	private final RedisTemplate redisTemplate;
	private final RabbitTemplate rabbitTemplate;

	@Override
	public Mono<ServerResponse> handle(ServerRequest serverRequest) {
		//生成验证码
		String text = RandomUtil.randomNumbers(4);

		//保存验证码信息
		String mobile = serverRequest.queryParam("mobile").get();
		redisTemplate.opsForValue().set(CommonConstants.DEFAULT_CODE_KEY + mobile, text, 90, TimeUnit.SECONDS);
		rabbitTemplate.convertAndSend(MqQueueConstant.MOBILE_CODE_QUEUE,
				new MobileMsgTemplate(
						mobile,
						text,
						CommonConstants.SMS_TEMPLATE
				));
		return ServerResponse
			.status(HttpStatus.OK)
			.contentType(MediaType.APPLICATION_JSON_UTF8)
			.body(BodyInserters.fromObject(BaseResultGenerator.success("发送成功")));
	}
}
